package com.wing.purchase.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.enums.PurEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.PurQualityTestingTask;
import com.wing.purchase.model.entity.PurQualityTestingTaskDetail;
import com.wing.purchase.model.response.PurQualityTestingTaskDetailVo;
import com.wing.purchase.service.PurQualityTestingTaskService;
import com.wing.sell.model.entity.FinishedOrder;
import com.wing.sell.model.entity.Order;
import com.wing.sell.model.entity.SelBarterGoodsRecords;
import com.wing.sell.model.entity.SelBarterGoodsRecordsDetail;
import com.wing.sell.model.request.SelBarterGoodRecordsUpdateForm;
import com.wing.sell.model.request.SelGoodsLogisticsDetailAddForm;
import com.wing.sell.model.response.SelBarterGoodRecordsSearchVo;
import com.wing.sell.model.response.SelBarterGoodsRecordDetailVo;
import com.wing.sell.service.FinishedOrderService;
import com.wing.sell.service.OrderService;
import com.wing.sell.service.SelBarterGoodsRecordsDetailService;
import com.wing.sell.service.SelBarterGoodsRecordsService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-11-16 11:05
 **/
@Api(value = "Admin-采购-质检任务", tags = "#/purchase/purQuality/purQualityTask")
@RestController("purQualityTestingTaskController")
@RequestMapping("purchase/admin/purQualityTask")
@RequiredArgsConstructor
@Slf4j
public class PurQualityTestingTaskController {

    private final PurQualityTestingTaskService purQualityTestingTaskService;

    @ApiOperation(value = "查询所有采购质检任务", notes = "搜索-质检任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<PurQualityTestingTask> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String sourceType
            ,String supplierId
            ,String code
            ,String orderCode
            ,String qualityTestingCategoryId
            ,String startTime
            ,String endTime
    ){

        Page<PurQualityTestingTask> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("sourceType", sourceType);
        params.put("supplierId", supplierId);
        params.put("code", code);
        params.put("orderCode", orderCode);
        params.put("qualityTestingCategoryId", qualityTestingCategoryId);
        params.put("startTime", startTime);
        params.put("endTime", endTime);

        IPage<PurQualityTestingTask> list = purQualityTestingTaskService.pageList4app(pg,params);
        List<PurQualityTestingTask> records = list.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            for (PurQualityTestingTask record : records) {
                record.setSourceTypeName(ProductEnum.purSourceTypeEmum.getNameByCode(record.getSourceType()));
                record.setStatusName(MaintenanceEnum.QualityStatus.getNameByCode(Integer.parseInt(record.getStatus())));
            }
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 添加采购任务
     * @param purQualityTestingTask 采购任务
     * @return
     */
    @ApiOperation(value = "添加采购任务", notes = "添加-采购任务")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody PurQualityTestingTask purQualityTestingTask) {
        if (ObjectUtil.isEmpty(purQualityTestingTask.getSubmissionQuantity())) {
            return JsonResult.fail("送检数量必填！");
        }

        if (purQualityTestingTaskService.addQualityTestingTask(purQualityTestingTask) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "作废采购任务", notes = "作废-任务")
    @PostMapping("/voidBy/{taskId}")
    public JsonResult voidBy(@PathVariable("taskId") String taskId) {
        PurQualityTestingTask byId = purQualityTestingTaskService.getById(taskId);
        if (ObjectUtil.isEmpty(byId)){
            return JsonResult.fail("未查询到数据！");
        }
        if (!byId.getStatus().equals(String.valueOf(MaintenanceEnum.QualityStatus.DRL.getCode()))){
            return JsonResult.fail("只有待认领状态的可作废！");
        }
        byId.setStatus(MaintenanceEnum.QualityStatus.ZF.getCode()+"");
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean b = purQualityTestingTaskService.updateById(byId);
        if (!b){
            return JsonResult.fail("作废失败！");
        }
        return JsonResult.success("作废成功！");
    }

    /**
     * 查询采购质检详情
     * @param taskId 任务id
     * @return
     */
    @ApiOperation(value = "采购质检详情", notes = "采购-详情")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/detail/{taskId}")
    public JsonResult<PurQualityTestingTaskDetailVo> detail(@PathVariable("taskId") String taskId) {
        PurQualityTestingTaskDetailVo purQualityTestingTaskDetailVo = purQualityTestingTaskService.detail(taskId);
        if (ObjectUtil.isNotNull(purQualityTestingTaskDetailVo)) {
            purQualityTestingTaskDetailVo.setSourceTypeName(ProductEnum.purSourceTypeEmum.getNameByCode(purQualityTestingTaskDetailVo.getSourceType()));
            purQualityTestingTaskDetailVo.setStatusName(MaintenanceEnum.QualityStatus.getNameByCode(Integer.parseInt(purQualityTestingTaskDetailVo.getStatus())));
        }
        return JsonResult.success(purQualityTestingTaskDetailVo);
    }

    /**
     * 认领质检任务
     * @param recordId
     * @return
     */
    @ApiOperation(value = "认领质检任务", notes = "认领-任务")
    @GetMapping("/claim/{recordId}")
    public JsonResult update(@PathVariable("recordId") String recordId) {
        PurQualityTestingTask byId = purQualityTestingTaskService.getById(recordId);
        if (ObjectUtil.isEmpty(byId)){
            return JsonResult.fail("未查询到质检任务信息！");
        }
        int isOk =  purQualityTestingTaskService.claim(recordId);
        if (isOk>0){
            return JsonResult.success("认领成功！");
        }else{
            return JsonResult.fail("认领失败！");

        }
    }
}
